const express = require("express")
const log = require("../middleware/log")
const loginApp = express()
const User = require("../model/User")
const { resErr, resSuccess } = require("../public/tip.js")
const request = require("request")
const bcrypt = require("bcryptjs")
const crypto = require("crypto")
const CryptoJS = require("crypto-js")
const Notice = require("../model/Notice")
// 登录
loginApp.post("/login", async (req, res) => {
  const { username, password } = req.body
  const user = (await User.findOne(username))[0]
  if (!user) return res.send({ ...resErr, msg: "帐号或密码错误" })
  let hashedPassword = await bcrypt.hash(password, user.salt)
  if (user.password !== hashedPassword) return res.send({ ...resErr, msg: "帐号或密码错误" })
  // if(new Date().getTime() > new Date(user.vip_expire_time).getTime()) return res.send({ ...resErr, msg: "会员已到期" })
  const token = await crypto.randomBytes(16).toString("hex")
  // 跟新token
  const user_token = await User.updateUserToken(user.id, token)
  res.send({ ...resSuccess, msg: "登录成功", data: { token, username: user.username, vip_expire_time: user.vip_expire_time, nickname: user.nickname } })
})

// 用户注册
loginApp.post("/register", async (req, res) => {
  let { username, password, nickname } = req.body
  username = decryptDES(username, "xiaoliu")
  const user = (await User.findOne(username))[0]
  if (user) {
    res.send({ ...resErr, msg: "用户已存在" })
  } else {
    const salt = await bcrypt.genSalt(10)
    const hashedPassword = await bcrypt.hash(password, salt)
    const vip_expire_time = new Date() // 获取当前时间
    vip_expire_time.setHours(vip_expire_time.getHours() + 1) // 将当前时间加上1小时
    await User.doRegister(username, hashedPassword, vip_expire_time, salt, nickname)
    res.send({ ...resSuccess, msg: "用户注册成功" })
  }
})
// 修改用户到期时间和密码
loginApp.post("/editExpirationTime", async (req, res) => {
  const { id, vip_expire_time, password } = req.body
  let user = ""
  if (password) {
    const salt = await bcrypt.genSalt(10)
    const hashedPassword = await bcrypt.hash(password, salt)
    user = await User.updateUserPasswordAdmin(id, vip_expire_time, hashedPassword, salt)
  } else {
    user = await User.updateVipExpireTime(id, vip_expire_time, password)
  }

  if (user) {
    res.send(resSuccess)
  } else {
    res.send(resErr)
  }
})

function decryptDES(encryptedText, key) {
  const keyHex = CryptoJS.enc.Utf8.parse(key)
  const decrypted = CryptoJS.DES.decrypt(
    {
      ciphertext: CryptoJS.enc.Base64.parse(encryptedText),
    },
    keyHex,
    {
      mode: CryptoJS.mode.ECB,
      padding: CryptoJS.pad.Pkcs7,
    }
  )
  return decrypted.toString(CryptoJS.enc.Utf8)
}
// 用户删除
loginApp.post("/delete", async (req, res) => {
  const { id } = req.body
  const user = await User.deleteUser(id)
  console.log(user)
  if (user) {
    res.send(resSuccess)
  } else {
    res.send(resErr)
  }
})

// 忘记密码
loginApp.post("/forgot", async (req, res) => {
  let { username, password, nickname } = req.body
  username = decryptDES(username, "xiaoliu")
  console.log(username)
  let user = (await User.findOne(username))[0]
  if (user) {
    if (user.nickname === nickname) {
      const hashedPassword = await bcrypt.hash(password, user.salt)
      const user_res = await User.updateUserPassword(user.id, hashedPassword)
      res.send(resSuccess)
    } else {
      res.send(resErr)
    }
  } else {
    res.send({ ...resErr, msg: "用户不存在" })
  }
})

//查询用户
loginApp.get("/userList", async (req, res) => {
  let { keyword, pageNum, pageSize } = req.query
  pageSize = Number(pageSize)
  const currentPage = (Number(pageNum) - 1) * pageSize
  try {
    const users = await User.findAll(keyword, currentPage, pageSize)
    const users_count = await User.count(keyword)
    res.send({ ...resSuccess, msg: "查询成功", data: users, total: users_count })
  } catch {
    res.send({ ...resErr })
  }
})

// 修改密码
loginApp.post("/changePwd", async (req, res) => {
  let { token } = req.headers
  let { newPwd, oldPwd } = req.body
  let user = await Notice.verifyToken(token)
  if (user.length > 0) {
    const hashedPassword = await bcrypt.hash(newPwd, user[0].salt)
    const user_res = await User.updateUserPassword(user.id, hashedPassword)
    res.send(resSuccess)
  } else {
    res.send(resErr)
  }
})

loginApp.get("/logout", (req, res) => {
  req.log = { handle: "退出" }
  log.insertLog(req)
  res.send(resSuccess)
})

module.exports = loginApp
